package org.lql.algo.codecrush.week003;

import org.lql.algo.common.ListNode;

/**
 * @author: liangqinglong
 * @date: 2025-07-30 15:45
 * @description: LCR 140. 训练计划 II <a href="https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/description/">...</a>
 **/
public class TrainingPlan {

    /**
     * 给定一个头节点为 head 的链表用于记录一系列核心肌群训练项目编号，请查找并返回倒数第 cnt 个训练项目编号。
     * <p>
     * <p>
     * <p>
     * 示例 1：
     * <p>
     * 输入：head = [2,4,7,8], cnt = 1
     * 输出：8
     * <p>
     * <p>
     * 提示：
     * <p>
     * 1 <= head.length <= 100
     * 0 <= head[i] <= 100
     * 1 <= cnt <= head.length
     */
    public ListNode trainingPlan(ListNode head, int cnt) {
        // 快慢指针
        ListNode fast = head;
        ListNode slow = head;
        // 快指针先移动 cnt 步
        while (cnt-- > 0) {
            fast = fast.next;
        }
        // 快慢指针同时移动，直到快指针到达链表末尾
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(2);
        head.next = new ListNode(4);
        head.next.next = new ListNode(7);
        head.next.next.next = new ListNode(8);
        ListNode res = new TrainingPlan().trainingPlan(head, 1);
        System.out.println(res.val);
    }
}
